importClass(java.io.File)


module.exports = function () {
    
    this.__name__ = "gitee"
    this.__debug__ = false
    this.__store__ = null
    this.branch = "master"
    // 工作目录
    this.__workPath__ = files.cwd()
    // 初始化状态
    this.__initState__ = false
    this.__version__ == "beta 0.1"


    this.log = function () {
        if (this.__debug__) {
            jscode = "print("
            // print(arguments.length)
            for (let i = 0;i < arguments.length; i++) {
                jscode += "\"" + arguments[i] + "\""
                if (i < arguments.length-1) jscode += ", ";
            }
            jscode += ")"
            eval(jscode)
        }
    }

    this.toast = function (str) {
        if (this.__debug__) toastLog(str);
    }
    
    this.getVersion = function () {
        return this.__version__
    }
    
    this.setDebug = function (r) {
        if (!r) return;
        if (r.constructor === Boolean) this.__debug__ = r;
    }
    
    this.init = function (url, token) {
        url = url.replace("//", "")
        
        if (url == "" || url == null || token == "" || token == null) throw "参数不正确";


        if (url.split("/").length != 3) throw "url格式错误";

        this.owner = url.split("/")[1]
        this.repo = url.split("/")[2]
        this.__store__ = storages.create(this.repo)
        
        this.__workPath__ = files.join(files.cwd(), this.repo)

        this.token = token
        this.__initState__ = true
            
        http.__okhttp__.setMaxRetries(0)
        http.__okhttp__.setTimeout(10*1000)
    }
    

    /***
     * 获取gitee file tree 如果返回的数组长度为0，就是获取失败
     */
    this.__getTree__ = function () {
        // 是否使用递归
        let recursive = 1;
        let api = 'https://gitee.com/api/v5/repos/'+this.owner+'/'+this.repo+'/git/trees/'+this.branch+'?access_token='+this.token+'&recursive='+recursive
        let res = http.get(api)
        if (res.statusCode == 200) {
            return res.body.json().tree
        } else {
            return null
        }
    }

    /***
     * @param {要转换的base字符串} str
     */
    this.__base2string__ = function (str) {
        return new java.lang.String(android.util.Base64.decode(new java.lang.String(str).getBytes(), android.util.Base64.DEFAULT))
    }

    /***
     * @param {要转换的base字符串} str
     */
    this.__base2bytes__ = function (str) {
        return android.util.Base64.decode(new java.lang.String(str).getBytes(), android.util.Base64.DEFAULT)
    }

    /***
     * 获取gitee 文件 bolds
     */
    this.__getBolds__ = function (sha) {
        let api = 'https://gitee.com/api/v5/repos/'+this.owner+'/'+this.repo+'/git/blobs/'+sha+'?access_token='+this.token
        let res = http.get(api)
        if (res.statusCode == 200) {
            return res.body.json()
        } else {
            return null
        }
    }

    /**
     * 
     * @param {gitee tree data} tree 
     * @returns 将tree与本地dir list比对 输出本地没有的gitee文件
     */
    this.__compdevscript__ = function (tree) {
        let result = []
        for (let i = 0; i<tree.length;i++) {
            if (tree[i]) {
                if (tree[i].type == "tree") continue;
                file_path = files.join(this.__workPath__, tree[i].path)
                if (!files.isFile(file_path)) result.push(tree[i]);
            }
        }
        return result
    }

    /**
     * 
     * @param {gitee返回的tree} tree 
     * 清理非gitee文件
     */
    this.__cleartemp__ = function (tree) {
        let f = new File(this.__workPath__)
        if (!f.exists()) {
            this.log("工作目录不存在")
            return null
        }
        let fs = f.listFiles()
        for (let i = 0; i<fs.length; i++) {
            let sign = false
            for (let j = 0; j<tree.length; j++) {
                if (fs[i] != null && tree[j] != null) {
                    let tpath = files.join(this.__workPath__, tree[j].path)
                    if (tpath == fs[i]) {
                        sign = true
                        break
                    }
                }
            }
            if (!sign) {
                // 开始删除文件或文件夹
                if (files.isFile(fs[i])) {
                    this.log("remove file -->> %s", fs[i])
                    files.remove(fs[i])
                } else if (files.isDir(fs[i])) {
                    this.log("remove folder -->> %s", fs[i])
                    files.removeDir(fs[i])
                }
            }
        }
        
    }

    // 去重tree
    this.__filter__ = function (newtree, tree) {
        result = []
        for (let i = 0;i < newtree.length; i++) {
            sign = false
            for (let j = 0;j < tree.length; j++) {
                if (newtree[i] != null && tree[i] != null) {
                    if (newtree[i].sha == tree[i].sha) {
                        sign = true
                        break
                    }
                }   
            }
            if (!sign) {
                result.push(newtree[i])
            }
        }
        return result
    }

    this.__resobj__ = function (code, message, fs) {
        if (!fs) fs = []
        return {
            code: code,
            message: message,
            fs: fs
        }
    }
    // 开始下载文件
    this.__downloadCodes__ = function() {
        let newtree = null
        
        let tree = this.__getTree__()
        if (tree == null) return null;


        this.log("---tree----")
        this.log(tree)
        this.log("---tree----")


        // 清理本地缓存
        this.__cleartemp__(tree)
        // 与本地保存的tree对比 挑出更新的文件
        if (this.__store__.contains("tree")) {
            newtree = this.__filter__(tree, this.__store__.get("tree"))
        } else {
            newtree = tree
        }
        this.__store__.put("tree", tree)
        
        // 兼容本地文件
        newtree = this.__compdevscript__(tree).concat(newtree)
        if (newtree.length == 0) {
            return this.__resobj__(0, "已是最新版本！")
        }

        // 开始下载更新内容到本地。
        newtree.forEach((res, index) => {
            if (!res) return;

            let savePath = files.join(this.__workPath__, res.path)
            
            // this.log(savePath)           
            // files.ensureDir(savePath)
            if (res.type == "blob") {

                this.log("start updataing %s file", res.path)
                // 获取文件内容
                if (res.path.split(".")[1] == "gif") {
                    return
                    
                }
                let bolds = this.__getBolds__(res.sha)
                if (bolds != null) {
                    files.createWithDirs(savePath)
                    
                    files.writeBytes(savePath, this.__base2bytes__(bolds.content))
                } else {
                    
                    console.error("gitee content is null")
                }
                
            } else if (res.type == "tree") {
                // 如果本地有同名文件需要删掉
                if (files.isFile(files.join(this.__workPath__, savePath))) {

                    files.remove(files.join(this.__workPath__, savePath))
                }
                if (!files.isDir(savePath+"/")) {
                    if (files.create(savePath+"/")) {
                        this.log("folder created success")
                    } else {
                        this.log("folder created fail")
                    }
                }
                

            }
        })
        return this.__resobj__(1, "更新了"+newtree.length+"个文件。", newtree)
    }

    /**
     * 清除本地存储数据
     */
    this.clearstore = function () {
        this.__store__.clear()
    }

    // 开始运行云端脚本项目
    this.run = function (scriptName) {
        if (!this.__initState__) throw "not init";
        this.log("start download codes")

        let downres = this.__downloadCodes__()
        this.toast(downres.message)
        
        let tagerScript = files.join(this.__workPath__, scriptName)
        
        this.log("开始运行%s脚本", scriptName)
        this.log("tagerScript -->> %s", tagerScript)

        print(engines.stopAll())
        
        /*
        engines.execScriptFile(tagerScript, {
            path: this.__workPath__
        })
        */
        
        if (ui.isUiThread()) {
            ui.finish()
        }
        
    }
}